@file:OptIn(ExperimentalForeignApi::class)

package com.jetbrains.kmpapp.feature.ads

import cocoapods.Ads_CN.BUAdError
import cocoapods.Ads_CN.BUAdSDKConfiguration
import cocoapods.Ads_CN.BUAdSDKManager
import cocoapods.Ads_CN.BUInteractionType
import cocoapods.Ads_CN.BUSplashAd
import cocoapods.Ads_CN.BUSplashAdCloseType
import cocoapods.Ads_CN.BUSplashAdDelegateProtocol
import cocoapods.Ads_CN.useMediation
import com.jetbrains.kmpapp.platform.currentRootViewController
import com.jetbrains.kmpapp.platform.size
import com.jetbrains.kmpapp.utils.loggers
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import platform.Foundation.NSError
import platform.UIKit.UIApplication
import platform.UIKit.UIScreen
import platform.darwin.NSObject
import kotlin.concurrent.Volatile


actual object AdsManager {
    private val scope by lazy { MainScope() }
    private val semaphore = Semaphore(1)
    private val splashAdDelegate by lazy { SplashAdDelegate() }

    @Volatile
    private var isInitialized: Boolean = false

    private val logger by loggers()

    actual fun showSplashAd() {
        scope.launch {
            if (!initialize()) {
                return@launch
            }

            val ad = BUSplashAd(slotID = "102667693", UIScreen.mainScreen.size)
            ad.delegate = splashAdDelegate
            ad.loadAdData()
        }
    }

    private suspend fun initialize(): Boolean {
        return semaphore.withPermit {
            val completion = CompletableDeferred<Boolean>()

            if (isInitialized) {
                completion.complete(true)
            } else {
                val config = BUAdSDKConfiguration()

                config.appID = "5477208"
                config.useMediation = true

                BUAdSDKManager.startWithSyncCompletionHandler { success, error ->
                    isInitialized = success
                    completion.complete(success)

                    if (success) {
                        logger.debug("穿山甲初始化成功")
                    } else {
                        logger.error("穿山甲初始化失败：$error")
                    }
                }
            }

            completion.await()
        }
    }
}

private class SplashAdDelegate : NSObject(), BUSplashAdDelegateProtocol {
    private val logger by loggers()

    override fun splashAdLoadSuccess(splashAd: BUSplashAd) {
        logger.debug("广告加载成功")
        UIApplication.sharedApplication.currentRootViewController
            ?.let { controller ->
                splashAd.showSplashViewInRootViewController(controller)
            }
    }

    override fun splashAdLoadFail(
        splashAd: BUSplashAd,
        error: BUAdError?
    ) {
        logger.debug("广告加载失败：$error")
    }

    override fun splashAdRenderSuccess(splashAd: BUSplashAd) {

    }

    override fun splashAdViewControllerDidClose(splashAd: BUSplashAd) {

    }

    override fun splashDidCloseOtherController(
        splashAd: BUSplashAd,
        interactionType: BUInteractionType
    ) {
    }

    override fun splashAdDidClose(
        splashAd: BUSplashAd,
        closeType: BUSplashAdCloseType
    ) {
    }

    override fun splashAdRenderFail(
        splashAd: BUSplashAd,
        error: BUAdError?
    ) {
    }

    override fun splashAdWillShow(splashAd: BUSplashAd) {
    }

    override fun splashVideoAdDidPlayFinish(
        splashAd: BUSplashAd,
        didFailWithError: NSError?
    ) {
    }

    override fun splashAdDidShow(splashAd: BUSplashAd) {
    }

    override fun splashAdDidClick(splashAd: BUSplashAd) {
    }

}